package com.ibm.cps.model;

import java.util.Collection;
import java.util.Iterator;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.message.MessageFields;
import com.ibm.cps.sql.StreamingSqlParser;
import com.ibm.factories.DataSourceFactory;
import com.ibm.factories.PublishProcessorFactory;
import com.ibm.util.JSONUtility;
import com.ibm.util.SchemaCache;
import com.ibm.util.exception.CPSException;

public class SQLAdapter extends MetadataAdapter {

	private SchemaCache schemaCache;

	public SQLAdapter(DataSourceFactory factory, SchemaCache schemaCache, PublishProcessorFactory publishFactory) {
		super(factory, publishFactory);
		this.schemaCache = schemaCache;
	}

	/*
	 * { groupid: ..., name: ..., sql: ... }
	 */
	@Override
	public String adapt2Json(String sqlJson, String tenantid) throws CPSException {
		JsonNode object = JSONUtility.fromString(sqlJson);
		if (object.isArray()) {
			ArrayNode array = JSONUtility.newArrayNode();
			Iterator<JsonNode> ite = object.iterator();
			while (ite.hasNext()) {
				ObjectNode node = (ObjectNode) ite.next();
				JSONUtility.assignRandomValue(node, MessageFields.GROUPID);
				ArrayNode metaDataJson = StreamingSqlParser.parse(node, tenantid, dataSourceFactory, schemaCache);
				array.addAll(metaDataJson);
			}
			return array.toString();
		} else {
			ObjectNode node = (ObjectNode) object;
			JSONUtility.assignRandomValue(node, MessageFields.GROUPID);
			ArrayNode metaDataJson = StreamingSqlParser.parse(node, tenantid, dataSourceFactory, schemaCache);
			return metaDataJson.toString();
		}
	}

	@Override
	public Collection<String> adaptFromJson(Collection<String> allMetadatas, Collection<String> targetMetadatas)
			throws CPSException {
		return targetMetadatas;
	}

}
